#!/usr/bin/env python3
# This file a part of SHM. Copyright (C) Tom Li 2013.
# License: LGPL version 3 or later.

from sh import userdel, ln, chown, rm, setquota, rc_update
import os
from getpass import getpass
import argparse
import mysql.connector as db
from config import Config
CONFIG = "/var/shm/config"


def delete_user(username):
    try:
        userdel("-r", username)
    except Exception as e:
        print("Warning: %s" % e)


def delete_database(username):
    while 1:
        password = getpass("Enter root password of MySQL: ")
        try:
            conn = db.connect(host='localhost', user='root', password=password)
            break
        except:
            print("Wrong password, try again!")
            continue

    cursor = conn.cursor()

    try:
        cursor.execute(r"DROP DATABASE %s;" % (username))
    except Exception as e:
        print("Warning: %s" % e)

    try:
        cursor.execute(r"DROP USER '%s'@'localhost';"
                       % (username))
    except Exception as e:
        print("Warning %s" % e)
    conn.close()


def delete_quota(username):
    setquota("-u", username, 0, 0, "0", "0", "/home")


def disable_domain(username, domain):
    script_name = "php-fcgi-%s" % domain
    try:
        rm("/etc/nginx/sites-enabled/%s.conf" % domain)
    except Exception as e:
        print("Warning: %s" % e)
    rc_update("del", script_name)


def delete_domain(username, domain):
    try:
        rm("/etc/nginx/sites-enabled/%s.conf" % domain)
        rm("/etc/nginx/sites-available/%s.conf" % domain)
        os.system("/etc/init.d/php-fcgi-%s stop" % domain)
        rm("/etc/init.d/php-fcgi-%s" % domain)
    except Exception as e:
        print("Warning: %s" % e)
    domain_config = Config(CONFIG, username)
    domain_config.remove_domain(domain)


def delete_all_domain(username):
    domain_config = Config(CONFIG, username)
    domain = domain_config.domain[0]
    delete_domain(username, domain)


def main():
    parser = argparse.ArgumentParser(description="Delete a user")

    parser.add_argument("username",
                        action="store",
                        default=False,
                        help="Delete the user",
                        type=str)
    parser.add_argument("-q", "--quota",
                        action="store_true",
                        dest="quota",
                        default=False,
                        help="Remove the limit value of space usage for the user")

    results = parser.parse_args()
    if results.username:
        if results.quota:
            delete_quota(results.username)
        if not (results.quota):
            os.system("/etc/init.d/nginx stop")
            delete_all_domain(results.username)
            delete_user(results.username)
            delete_database(results.username)
            os.system("/etc/init.d/nginx start")


main()
